package dfl.bysj.controller;


import com.alibaba.excel.EasyExcel;
import dfl.bysj.entity.VO.ExcelDictDTO_Student;
import dfl.bysj.entity.VO.ExcelDictDTO_Teacher;
import dfl.bysj.exception.UnifiedException;
import dfl.bysj.result.R;
import dfl.bysj.result.ResponseEnum;
import dfl.bysj.service.TeacherService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author DFL
 * @since 2022-05-17
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/teacher")
public class TeacherController {

    private TeacherService teacherService;

    @Autowired
    public void setTeacherService(TeacherService teacherService) {
        this.teacherService = teacherService;
    }

    @ApiOperation("Excel批量导入数据字典")
    @PostMapping("/import")
    public R batchImport(
            @ApiParam(value = "Excel文件", required = true)
            @RequestParam("file") MultipartFile file) {

        try {
            InputStream inputStream = file.getInputStream();
            log.info(inputStream.toString());
            teacherService.importData(inputStream);
            return R.ok().message("批量导入成功");
        } catch (Exception e) {
            //UPLOAD_ERROR(-103, "文件上传错误"),
            log.error( e.getMessage());
            throw new UnifiedException(ResponseEnum.UPLOAD_ERROR, e);

        }
    }

    @ApiOperation("Excel数据的导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response) {

        try {
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("teacherDict", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ExcelDictDTO_Teacher.class).sheet("数据字典").doWrite(teacherService.listDictData());

        } catch (IOException e) {
            //EXPORT_DATA_ERROR(104, "数据导出失败"),
            throw new UnifiedException(ResponseEnum.EXPORT_DATA_ERROR, e);
        }
    }


    @GetMapping("/list")
    public R list(){
        return R.ok().data("list",teacherService.list());
    }
}

